﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

#if !WINRT
using System.Windows;
using System.Windows.Threading;
#else

using Windows.UI.Xaml;
#endif

namespace MishraReader.Windows.Controls
{
    public class AnimatedTile : StepControl
    {
        private readonly DispatcherTimer _timer;

        public AnimatedTile()
        {
            TileTransitionInterval = 3000;
            TileTransitionBeginTime = 0;

            _timer = new DispatcherTimer();
            _timer.Tick += _timer_Tick;

            Loaded += AnimatedTile_Loaded;
            Unloaded += AnimatedTile_Unloaded;
        }

        public int TileTransitionBeginTime { get; set; }
        public int TileTransitionInterval { get; set; }

        public void NextTile()
        {
            if (_timer.IsEnabled)
            {
                _timer.Stop();

                InternalNextTile();

                _timer.Interval = TimeSpan.FromMilliseconds(TileTransitionBeginTime);
                _timer.Start();
            }
        }

        private void InternalNextTile()
        {
            if (SelectedIndex < Items.Count - 1)
                SelectedIndex++;
            else
                SelectedIndex = 0;
        }

        private void AnimatedTile_Loaded(object sender, RoutedEventArgs e)
        {
            _timer.Interval = TimeSpan.FromMilliseconds(TileTransitionBeginTime);
            _timer.Start();
        }

        private void AnimatedTile_Unloaded(object sender, RoutedEventArgs e)
        {
            _timer.Stop();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            if (_timer.Interval == TimeSpan.FromMilliseconds(TileTransitionBeginTime))
                _timer.Interval = TimeSpan.FromMilliseconds(TileTransitionInterval);

            InternalNextTile();
        }
    }
}